package org.ilc.sample;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ilc.Bootstrap;
import org.ilc.FileLogger;
import org.ilc.push.*;
import org.ilc.push.exception.PushException;
import org.ilc.sample.task.ReadTask;
import org.ilc.sample.util.AccountValidator;
import org.ilc.sample.util.ValidateUtil;

import java.io.UnsupportedEncodingException;

/**
 * Simple session listener
 * @author malb
 * Date: 13-4-12
 * Time: 下午3:21
 */
public class SimpleSessionListener extends AbstractLogger implements ISessionListener {
    private static Log log = LogFactory.getLog("SimpleSessionListener");
    private static final String KEY="account";

    /**
     * Do something when session is created.
     * @param request
     * @throws org.ilc.push.exception.PushException
     */
    @Override
    public void sessionCreate(IRequest request) throws PushException {
        request.getSession().setAttribute(KEY, request.getHeader().getAuthUser());

//        System.out.println (request.getHeader ().getAuthUser () + " is comming......");
        //验证user合法性
//        String isValidate = Bootstrap.getContext ().getConfig ().get ("push.account.verify.enable");
        boolean isValidate = Bootstrap.getContext ().getAppConfig ().getBoolean (Constants.ACCONT_ISVALIDATE_KEY, true);
//        System.out.println("是否校验：" + isValidate);
        if (isValidate) {
            String account = request.getHeader ().getAuthUser ();
            String passwd = request.getHeader ().getAuthPwd ();
            String type = request.getHeader ("auth-type");
            String version = request.getHeader ("auth-version");
//            System.out.println("开始校验");
            boolean isRigth = false;
            try {
                isRigth = AccountValidator.validateUser(account, passwd, type, version);
            } catch (Exception e) {
                throw new PushException ("服务器校验用户失败", IHeader.SC_ERROR);
            }
//            System.out.println(account + " is " + isRigth);
//            System.out.println("校验结束");
            //验证非法
            if (!isRigth)
                throw new PushException ("非法用户", IHeader.SC_INVALID);

        }

        if(Bootstrap.getContext().getAppConfig().getBoolean(org.ilc.Constants.SERVER_DEBUG)) {
            new FileLogger().log(SimpleSessionListener.class, request.getHeader ().getAuthUser () + " login.");
        }
        //用户有效，检查未读消息
        ReadTask task = new ReadTask (request.getHeader ().getAuthUser ());
        Bootstrap.getContext ().getTaskQueue ().getQueue ().putTask (task);
//        CacheWork.readMsg (request.getHeader ().getAuthUser ());
    }

    /**
     * Do something when server has been received message.
     * @param request
     * @param response
     * @throws org.ilc.push.exception.PushException
     */
    @Override
    public void messageReceived(IRequest request, IResponse response) throws PushException {

        //获取消息接收者
        String users = request.getHeader ().getHeader ("receiver");
        if (users == null || "".equals (users)) return;

        users = users.replaceAll("，", ",");
        //将所有用户名转换为小写
        users = users.toLowerCase();

        String [] userArr = users.split (",");

//        System.out.println("server receive head: " + request.getHeader().toString());
//        System.out.println("server receive data: " + new String(request.getBody()));
//        System.out.println();
        //处理接收到的消息体
        try {
            String content = new String (request.getBody (),"utf-8");

            if(Bootstrap.getContext().getAppConfig().getBoolean(org.ilc.Constants.SERVER_DEBUG)) {
                new FileLogger().log(SimpleSessionListener.class,
                        request.getHeader ().getAuthUser () + " send message \"" + content + "\" to " + users);
            }

            if (!ValidateUtil.validateStr (content)) return;
//            System.out.println ("server receive: " + content);
            //转发消息
            for (String user : userArr) {
                try {
                    //将消息放入消息队列
                    Bootstrap.getContext ().getDataProvider ().cache (user, content);
                } catch (Exception e) {
                    if (log.isErrorEnabled())
                        log.error ("transmit message failed.",e);
                }
            }
        } catch (UnsupportedEncodingException e) {
            if (log.isErrorEnabled())
                log.error ("unsupport encoding while encode message",e);
            throw new PushException ("unsupport encoding while encode message", IHeader.SC_ERROR);
        }
    }

    /**
     * Do something when session is closed.
     * @param session
     */
    @Override
    public void sessionClose(ISession session) {
    }
}
